﻿using System;
using System.Collections.Generic;
using System.Linq;
using QConnectSDK;
using QConnectSDK.Models;
using System.IO;
using Aij1.Cms;
using Aij1.Model;
using DevExpress.Data.Filtering;
using System.Net;
using Aij1.Utils;
using Aij1.BLL;
using QConnectSDK.Context;

namespace Aij1
{
    public partial class GetQQInfo : BasePage
    {
        UserInfo userInfo;
        QOpenClient qzone;
        User currentUser;
        protected bool ShowInfo = true;
        protected string Tips;
        string authenticationUrl;
        string stateRequest;
        protected string OP;

        string code, state;
        protected void Page_Load(object sender, EventArgs e)
        {
            OP = CommOp.ToStr(Request.QueryString["OP"]);
            Keywords = "QQ号登录,一键登录,订购套系";
            Description = Config.CompanyName + ",使用QQ账号一键式登录，保证用户的私人信息安全。";
            if (IsPostBack)
            {
                AcceptUserChange();
                Tips = "您的个人资料已经修改成功。";
                PageName = "个人资料修改成功";
                OP = "editinfo";
                return;
            }

            switch (OP)
            {
                case "login":
                    GetRequestToken();
                    Response.Redirect(authenticationUrl);
                    break;
                case "logout":
                    WebHelper.RemoveCookie(AuthData.QQLoginIdName);
                    WebHelper.RemoveCookie("code");
                    WebHelper.RemoveCookie("state");
                    //Session.Remove("QZone");
                    Response.ContentType = "text/plain";
                    Response.Write("0");
                    Response.End();
                    break;
                case "editinfo":
                    Tips = "查看和修改您的个人资料。";
                    PageName = "修改个人资料";
                    break;
                case "sync":
                    SyncUserInfo();
                    Tips = "您的个人资料已经从您的QQ空间同步成功。";
                    PageName = "个人资料同步成功";
                    break;
                case "": //登录成功了
                    AfterLogin();
                    if (CurrentCustomer == null) //第一次登录
                    {
                        CurrentCustomer = new C_Customer(XpoSession);
                        CurrentCustomer.RegisterTime = DateTime.Now;
                        SyncUserInfo();
                        OP = "editinfo";
                        Tips = String.Format("欢迎您使用QQ账号登录<b>{0}</b>! 您是第一次登录，如果有必要请完善您的个人信息。", Config.CompanyName);
                        PageName = "欢迎您登录爱+1";
                    }
                    else
                    {
                        Tips = "欢迎您再次登录爱+1! ";
                        PageName = "欢迎再次登录";
                        ShowInfo = false;
                    }
                    AuthData.SetCurrentCustomer(CurrentCustomer);
                    break;
                default:
                    break;
            }
        }

        void Relogin()
        {
            Response.Write("您还没有从QQ登录或登录已过期. 系统3秒后自动转向QQ登录页面... <script>setTimeout(\"location='GetQQInfo.aspx?OP=login'\",3000)</script>");
            Response.End();
        }

        void AfterLogin()
        {
            code = Request.QueryString["code"];
            state = Request.QueryString["state"];
            qzone = new QOpenClient(code, state);
            try
            {
                currentUser = qzone.GetCurrentUser();
                WebHelper.SetCookie("code", code);
                WebHelper.SetCookie("state", state);
                //Session["QZone"] = qzone;
                userInfo = qzone.GetWeiboUserInfo().Data;
                CurrentCustomer = XpoSession.FindObject<C_Customer>(CriteriaOperator.Parse("QQLoginId=?", userInfo.Openid));
            }
            catch (Exception ex)
            {
                Response.Write("登录错误,可能是您长时间未操作引起登录过期，请重新登录。<br />错误信息:" + ex.Message);
                Response.End();
            }
        }

        private void AcceptUserChange()
        {
            CurrentCustomer.SysName = Request.Form["txtName"].Trim();
            CurrentCustomer.Tel = Request.Form["txtTel"].Trim();
            CurrentCustomer.Email = Request.Form["txtEmail"].Trim();
            CurrentCustomer.QQ = Request.Form["txtQQ"].Trim();
            CurrentCustomer.ReceiveAddr = Request.Form["txtReceiveAddr"].Trim();
            CurrentCustomer.Mobile = Request.Form["txtMobile"].Trim();
            CurrentCustomer.Gender = CommOp.ToInt(Request.Form["selGender"]);
            CurrentCustomer.Comment = CommOp.ToStr(Request.Form["txtComment"]);
            CurrentCustomer.Contact = CommOp.ToStr(Request.Form["txtContact"]);

            int childNo = 1;

            IList<C_Child> children = new List<C_Child>();
            while (!String.IsNullOrEmpty(Request.Form["txtChildName_" + childNo]))
            {
                C_Child child = null;
                int childId = CommOp.ToInt(Request.Form["hdnChildId_" + childNo]);
                if (childId > 0)
                {
                    child = XpoSession.GetObjectByKey<C_Child>(childId);
                }
                if (child == null)
                {
                    child = new C_Child(XpoSession)
                    {
                        SysName = CurrentCustomer.SysName + Config.GetUniqueName(),
                    };
                }

                child.Birth = CommOp.ToDateTime(Request.Form["txtChildBirth_" + childNo]);
                child.TrueName = Request.Form["txtChildName_" + childNo].Trim();
                child.Gender = CommOp.ToInt(Request.Form["selChildGender_" + childNo]);
                child.ParentId = CurrentCustomer;
                children.Add(child);
                childNo++;
            }

            foreach (var chd in CurrentCustomer.Children.Except(children).ToArray())
            {
                chd.Delete();
            }

            AuthData.CheckAndCreateSysName(CurrentCustomer);
            CurrentCustomer.Save();

        }

        private void GetRequestToken()
        {
            var context = new QzoneContext();
            stateRequest = Guid.NewGuid().ToString("N");
            string scope = "get_user_info,add_share,list_album,upload_pic,check_page_fans,add_t,add_pic_t,del_t,get_repost_list,get_info,get_other_info,get_fanslist,get_idolist,add_idol,del_idol,add_one_blog,add_topic,get_tenpay_addr";
            authenticationUrl = context.GetAuthorizationUrl(stateRequest, scope);
        }

        void SyncUserInfo()
        {
            string receiveAddr = "";// qzone.GetTenpayAddr();

            IEnumerable<S_Edu> edus = new List<S_Edu>();
            if (userInfo.Edu != null && userInfo.Edu.Count > 0)
            {
                edus = (from edu in userInfo.Edu
                        select new S_Edu(XpoSession)
                        {
                            Id = edu.Id,
                            DepartmentId = edu.Departmentid,
                            Level = edu.Level,
                            SchoolId = edu.Schoolid,
                            PersonId = CurrentCustomer,
                            Year = edu.Year,
                        });
            }
            CurrentCustomer.Location = userInfo.Location;
            CurrentCustomer.QQLoginId = userInfo.Openid;
            CurrentCustomer.Email = userInfo.Email;
            CurrentCustomer.Gender = currentUser.Gender == "男" ? 1 : 2;
            CurrentCustomer.Birth = new DateTime(userInfo.Birth_year, userInfo.Birth_month, userInfo.Birth_day);
            CurrentCustomer.TrueName = userInfo.Name;
            CurrentCustomer.SysName = currentUser.Nickname;
            CurrentCustomer.ReceiveAddr = receiveAddr;
            CurrentCustomer.CountryCode = userInfo.Country_code;
            CurrentCustomer.ProvinceCode = userInfo.Province_code;
            CurrentCustomer.CityCode = userInfo.City_code;
            CurrentCustomer.FansNum = userInfo.Fansnum;
            CurrentCustomer.IdolNum = userInfo.Idolnum;
            CurrentCustomer.Intro = userInfo.Introduction;
            CurrentCustomer.IsVip = userInfo.Isvip;
            CurrentCustomer.IsEnt = userInfo.Isent;
            CurrentCustomer.Level = currentUser.Level;
            CurrentCustomer.FigureUrl = currentUser.Figureurl;

            ((IList<S_Edu>)CurrentCustomer.Educations).Clear();
            CurrentCustomer.Educations.AddRange(edus);
            CurrentCustomer.Save();
        }

        /// <summary>
        /// Retrieve the content of a file in the local file system
        /// </summary>
        /// <param name="localFile">The local file to upload</param>
        /// <returns>True on success</returns>
        public byte[] GetFileContentFromFS(FileInfo localFile)
        {
            //Get the file stream
            byte[] bytes = null;
            FileStream fs = new FileStream(localFile.FullName, FileMode.Open, FileAccess.Read);
            BinaryReader br = new BinaryReader(fs);
            long numBytes = localFile.Length;
            bytes = br.ReadBytes((int)numBytes);
            fs.Close();
            return bytes;
        }
    }
}